import React, { Component } from 'react';

class FileInput extends Component {
  constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
  }
  handleSubmit(event) {
    event.preventDefault();
    alert(
      `Selected file - ${this.fileInput.files[0].name}`
    );
    // FormData 对象
    let form = new FormData();
    // 增加表单数据
    // form.append('param', JSON.stringify(param));
    // 流数据
    form.append('file', this.fileInput.files[0]);
    let xhr = new XMLHttpRequest();
    // 接收上传文件的后台地址
    let FileController = 'http://172.16.0.191:8000/upload';
    xhr.open('post', FileController, true);
    xhr.send(form);
    return new Promise((resolve, reject) => {
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
          if (xhr.status === 200) {
            alert(JSON.stringify(xhr));
            resolve(xhr || JSON.parse(xhr.responseText));
          } else {
            alert(JSON.stringify(xhr));
            reject(new Error(xhr.status));
          }
        }
      };
    });
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Upload file:
          <input
            type="file"
            name="myfile"
            ref={input => {
              this.fileInput = input;
            }}

          />

        </label>
        <br />
        <button type="submit">Submit</button>
      </form>
    );
  }
}

export default FileInput;
